//var getlocation = false;
var _Longitude = '';
var _Latitude = '';
var search ;
var token = localStorage.getItem("token");	

var map, geolocation;
//function getLocation(){
//  if (navigator.geolocation){
//      navigator.geolocation.getCurrentPosition(showPosition,showError);
//  }else{
//      alert("不支持定位"); 
//  }
//}

function getLocation(){
	hui.loading('定位中 ');
    //加载地图，调用浏览器定位服务
    map = new AMap.Map('', {
        resizeEnable: true
    });
    map.plugin('AMap.Geolocation', function() {
        geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：无穷大
            buttonOffset: new AMap.Pixel(10, 20),//定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
            zoomToAccuracy: true,      //定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            buttonPosition:'RB'
        });
        map.addControl(geolocation);
        geolocation.getCurrentPosition();
        AMap.event.addListener(geolocation, 'complete', onComplete);//返回定位信息
        AMap.event.addListener(geolocation, 'error', onError);      //返回定位出错信息
    });
}
//解析定位错误信息
    function onError(data) {
        console.log('定位失败');
        hui.loading(false, true);
		alert('定位失败')
        
    }
//function showError(error){ 
//	 switch(error.code) { 
//	    case error.PERMISSION_DENIED: 
//	      alert("定位失败,用户拒绝请求地理定位"); 
//		  break; 
//		case error.POSITION_UNAVAILABLE: 
//		  alert("定位失败,位置信息是不可用"); 
//		  break; 
//		case error.TIMEOUT: 
//		  alert("定位失败,请求获取用户位置超时"); 
//		  break; 
//		case error.UNKNOWN_ERROR: 
//		  alert("定位失败,定位系统失效"); 
//		      break; 
//	}	 
//}
function onComplete(data){
	hui.loading(false, true);
    console.log("Latitude: " + data.position.getLat() + "<br />Longitude: " + data.position.getLng());
    _Latitude = data.position.getLat();
	_Longitude = data.position.getLng();
    localStorage.setItem("Latitude",data.position.getLat());
    localStorage.setItem("Longitude",data.position.getLng()); 
    search = {
		'province':'',
		'city':'',
		'lng':_Longitude,
		'lat':_Latitude,
		'page':'1',
		'pagesize':'1'
	}
//  console.log(JSON.stringify(search))
    getbyposition(_Latitude,_Longitude);
    
    issign();
}

//获取医院
function getbyposition(_Latitude,_Longitude){
	console.log(JSON.stringify(search))
	hui.ajax({
	    type : 'POST',
	    url : globleobj['domain']+'/comhospital/getbyposition',
	    data : search,
	    beforeSend : function(){hui.loading();},
	    complete   : function(){hui.closeLoading();},
	    success : function(msg){
	    	var data = JSON.parse(msg)
	    	console.log(data)
	    	if(data.rc != 0){
	    		hui.toast(data.msg);
	    		return false;  
	    	}
	    	var headName = data.list[0].name; 
	    	hui(".mycoctor").html(headName);
//	    	('+JSON.stringify(data.list[i]).replace(/"/g, "&quot;")+')
			var  group_id =  [];
			for(var i = 0; i < data.list.length; i++){
				
				console.log(data.list[i]._id);
				group_id.push(data.list[i]._id);
			}
			console.log(group_id);
	    	getgroups(group_id);
	    },
	    error : function(e){
	        console.log(JSON.stringify(e));
	        hui.iconToast('读取消息失败', 'warn');
	    } 
	}); 
}
//('5af566d19d2c28de846f22a3,5af566d19d2c28de846f22a7')
//获取医院所有医生组
function getgroups(groupIds){
	console.log(groupIds.join(','));
	groupIds = ['5af566d19d2c28de846f22a3','5af566d19d2c28de846f22a7']
	hui.ajax({
	    type : 'POST',
	    url : globleobj['domain']+'/comhospital/getgroups',
	    data : {'group_ids':groupIds},
	    beforeSend : function(){hui.loading();},
	    complete   : function(){hui.closeLoading();},
	    success : function(msg){
	    	var data = JSON.parse(msg)
	    	console.log(data)
	    	if(data.rc != 0){
	    		hui.toast(data.msg);
	    		return false; 
	    	}
	    	var options = ''; 
	    	var dataLength = data.list.length > 2 ? 2 :data.list.length;
	    	for(var i= 0;i< dataLength; i++){
	    		options += '<li  onclick="teamDetails('+JSON.stringify(data.list[i]).replace(/"/g, "&quot;")+','+false+')">'
								+'<a href="javascript:void(0)">'
									+'<div class="hui-media-list-img">'
										+'<img src="../../img/teamDoct.png" />'
									+'</div>'
									+'<div class="hui-media-content">'
										+'<h1>'+data.list[i].captain.name+'</h1>'
										+'<p>'+data.list[i].captain.specialty+'</p>'
									+'</div>'
								+'</a>'
							+'</li>'
	    	}
	    	hui('#allsign').html(options);
	    	
	    },
	    error : function(e){
	        console.log(JSON.stringify(e));
	        hui.iconToast('读取消息失败', 'warn');
	    } 
	}); 
}
//否已签约
function issign(){
	hui.ajax({
	    type : 'POST',
	    url : globleobj['domain']+'/residents/issign',
	    data : {'token':token},
	    beforeSend : function(){hui.loading();},
	    complete   : function(){hui.closeLoading();},
	    success : function(msg){
	    	console.log(msg) 
	    	var data = JSON.parse(msg);
	    	localStorage.setItem("rc",data.rc);
	    	if(data.rc == 1){ 
	    		localStorage.setItem("rc",data.rc);
	    		hui('.issignNo').hide();
    			var options = '<li class="teamDetails" onclick="teamDetails('+JSON.stringify(data.group_info).replace(/"/g, "&quot;")+','+true+')">'
								+'<a href="javascript:void(0)">'
									+'<div class="hui-media-list-img">'
										+'<img src="../../img/teamDoct.png" />'
									+'</div>'
									+'<div class="hui-media-content">'
										+'<h1>'+data.group_info.name+'</h1>'
										+'<p>'+data.group_info.hos_name+'</p>'
									+'</div>'
								+'</a>'
							+'</li>'
	    	}
	    	hui('#issign').html(options);
	    	
	    },
	    error : function(e){
	        console.log(JSON.stringify(e));
	        hui.iconToast('读取消息失败', 'warn');
	    } 
	}); 
}


function teamDetails(captain,num){
//	console.log(JSON.stringify(captain))
//	console.log(num)
	var captain = JSON.stringify(captain);
	localStorage.setItem("captain",captain);
	localStorage.setItem("issignNum",num);
	hui.open('/html/helthy/teamDetails.html',{},true); 
}

hui.ready(function(){
	
	if(localStorage.getItem('Latitude')){
		
		 search = {
			'province':'',
			'city':'',
			'lng':localStorage.getItem('Longitude'),
			'lat':localStorage.getItem('Latitude'),
			'page':'1',
			'pagesize':'1'
		}
		getbyposition(localStorage.getItem('Latitude'),localStorage.getItem('Longitude'));
		issign(); 
	}else{		
		
		getLocation();
	}
	hui('#hui-back').click(function(){
	    //hui.open('../homepage.html',{},true);
	});
		
	
	
	//跳转团队详情
//	hui('.teamDetails').click(function(){
//	    hui.open('teamDetails.html');
//	});
	//选项卡
	hui.tab('.hui-tab');
	
//  hui.plusReady(function(){
      	//console.log('plusReady');
    	//跳转社区筛选
		hui('#goCommunitycity').click(function(){
		    hui.open('/html/helthy/communitycity.html',{},true);
		});
			
		//跳转社区筛选
		hui('#look').click(function(){
		    hui.open('/html/helthy/moreTearm.html',{},true);
		});
//  });
});